package com.nowcoder.community.controller;

import com.nowcoder.community.annotation.LoginRequired;
import com.nowcoder.community.entity.Comment;
import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.Page;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.*;
import com.nowcoder.community.utils.CommunityConstant;
import com.nowcoder.community.utils.CommunityUtil;
import com.nowcoder.community.utils.HostHolder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController implements CommunityConstant {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Value("${community.path.domain}")
    private String domain;

    @Value("${community.path.upload}")
    private String uploadPath;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private UserService userService;


    @Autowired
    private LikeService likeService;

    @Autowired
    private FollowService followService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private DiscussPostService discussPostService;

    @LoginRequired
    @RequestMapping(path = "/setting", method = RequestMethod.GET)
    public String getSettingPage() {
        return "/site/setting";
    }

    /**
     * 实现上传头像的请求，并在上传成功后，更新用户的头像路径
     *
     * @param model
     * @param headerImage
     * @return
     */
    @LoginRequired
    @RequestMapping(path = "/upload", method = RequestMethod.POST)
    public String uploadheaderImg(Model model, MultipartFile headerImage) {
        //对headerImage判空
        if (headerImage == null) {
            model.addAttribute("error", "你还没有选择图片！");
            return "/site/setting";
        }
        //更改文件名为xxx.png/xxx..jpg
        String fileName = headerImage.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf('.'));


        if (StringUtils.isBlank(suffix)) {
            model.addAttribute("error", "文件格式不正确");
            return "/site/setting";
        }
        //随机文件名
        String newFileName = CommunityUtil.generateUUID() + suffix;
        //确定文件存放路径
        File dest = new File(uploadPath + "/" + newFileName);
        //存储文件
        try {
            headerImage.transferTo(dest);
        } catch (IOException e) {
            logger.error("上传文件失败！" + e.getMessage());
            throw new RuntimeException("上传文件失败，服务器发生错误");
        }


        //服务层把头像路径进行更新
        //http://localhost:8080/community/user/header/xxx.png
        User user = hostHolder.getUser();
        String newHeaderURL = domain + contextPath + "/user/header/" + newFileName;
        userService.updateHeaderUrl(user.getId(), newHeaderURL);
        //更新成功，就重新回到登录页面
        return "redirect:/index";
    }

    /**
     * 在重定向到index页面后，拦截器会对th:src = http://localhost:8080/community/user/header/xxx.png 作出get请求
     * 此时该请求会由该controller接受，最终完成头像的更换
     * 实现获取头像的请求
     *
     * @param fileName
     * @param response
     */
    @RequestMapping(path = "/header/{fileName}", method = RequestMethod.GET)
    public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response) {

        //服务器存放路径
        fileName = uploadPath + "/" + fileName;
        //文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        //响应图片
        response.setContentType("image/" + suffix);

        try (
                FileInputStream inputStream = new FileInputStream(fileName);
                OutputStream outputStream = response.getOutputStream();
        ) {
            byte[] bytes = new byte[1024];
            int b = 0;
            while ((b = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, b);
            }
        } catch (IOException e) {
            logger.error("读取头像失败：" + e.getMessage());
        }
    }

    /**
     * @param model
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @RequestMapping(path = "/password", method = RequestMethod.POST)
    public String changePassword(Model model, String oldPassword, String newPassword) {

        if (StringUtils.isBlank(oldPassword)) {
            model.addAttribute("oldPassword", "原密码不能为空！");
            return "/site/setting";
        }
        if (StringUtils.isBlank(newPassword)) {
            model.addAttribute("newPassword", "新密码不能为空！");
            return "/site/setting";
        }
        //获取当前用户
        User user = hostHolder.getUser();
        if (userService.testPassword(user, oldPassword)) {
            //原密码正确，修改密码为新密码

            userService.updatePassword(user.getId(), CommunityUtil.md5(newPassword + user.getSalt()));
            return "redirect:/logout";
        } else {
            //原密码错误
            model.addAttribute("oldPassword", "原密码不正确！");
            return "/site/setting";
        }
    }

    /**
     * 个人主页
     * @param userId
     * @param model
     * @return
     */
    @RequestMapping(path = "/profile/{userId}", method = RequestMethod.GET)
    public String getProfilePage(@PathVariable("userId") int userId, Model model) {
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在");
        }
        //用户
        model.addAttribute("user", user);
        //点赞数量
        model.addAttribute("likeCount", likeService.findUserLikeCount(userId));

        //我的关注数量
        long followeeCount = followService.findFolloweeCount(userId, ENTITY_TYPE_USER);
        model.addAttribute("followeeCount", followeeCount);
        //我的粉丝数量
        long followerCount = followService.findFollowerCount(ENTITY_TYPE_USER, userId);
        model.addAttribute("followerCount", followerCount);
        //是否已关注
        boolean hasFollowed = false;
        if (hostHolder.getUser() != null) {
            hasFollowed = followService.hasFollower(hostHolder.getUser().getId(),ENTITY_TYPE_USER,userId);
        }
        model.addAttribute("hasFollowed", hasFollowed);
        return "/site/profile";
    }

    /**
     * 我发布的帖子
     * @param userId
     * @param page
     * @param model
     * @return
     */
    @RequestMapping(path = "/mypost/{userId}",method = RequestMethod.GET)
    public String getMyPostPage(@PathVariable("userId") int userId, Page page, Model model, @RequestParam(name = "orderMode",defaultValue = "0") int orderMode){
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在");
        }
        model.addAttribute("user",user);
        //分页
        page.setLimit(5);
        page.setPath("/user/mypost/" + userId);
        page.setRows(discussPostService.findDiscussPostRows(userId));

        //帖子列表
        List<DiscussPost> postList = discussPostService.findDiscussPosts(userId,page.getOffset(),page.getLimit(),orderMode);
        List<Map<String,Object>> posts = new ArrayList<>();
        if (postList != null){
            for (DiscussPost post:postList){
                Map<String, Object> map = new HashMap<>();
                map.put("post",post);
                //帖子获得的赞
                long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId());
                map.put("likeCount",likeCount);
                posts.add(map);
            }
        }
        model.addAttribute("posts",posts);
        return "/site/my-post";
    }

    /**
     * 我发布的评论
     * @param userId
     * @param page
     * @param model
     * @return
     */
    @RequestMapping(path = "/myreply/{userId}",method = RequestMethod.GET)
    public String getMyReplyPage(@PathVariable("userId") int userId, Page page,Model model){
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在");
        }
        model.addAttribute("user",user);
        //分页

        page.setPath("/user/myreply/" + userId);
        page.setRows(commentService.findUserCount(userId));

        //帖子列表
        List<Comment> replyList = commentService.findUserComments(userId,page.getOffset(),page.getLimit());
        List<Map<String,Object>> commentVOList = new ArrayList<>();
        if (replyList != null){
            for (Comment comment:replyList){
                Map<String, Object> map = new HashMap<>();
                map.put("comment",comment);
                //我评论回复的帖子
                DiscussPost post = discussPostService.findDiscussPostById(comment.getEntityId());
                map.put("discussPost",post);
                commentVOList.add(map);
            }
        }
        model.addAttribute("comments",commentVOList);
        return "/site/my-reply";
    }


}
